package com.carlinfo.shop.back.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.carlinfo.shop.common.util.ConstatFinalUtil;
import com.carlinfo.shop.common.util.PageInfoUtil;
import com.carlinfo.shop.common.web.controller.BaseController;
import com.carlinfo.shop.goods.service.IGoodsService;

/**
 * 后台统计的Controller
 * @author wangshMac
 */
@Controller
@RequestMapping("/back/stat///")
public class StatBackController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	
	/**
	 * 商品统计
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/goodsList")
	public String goodsList(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.LOGGER.info("==goodsList==");
		this.goodsListJSON(request);
		/* 要下载的时候,额外的加一个参数 */
		String operType = request.getParameter("operType");
		if("downloadfile".equalsIgnoreCase(operType))
		{
			/* 告诉 浏览器,不管是不是可以打开,都弹出下载框 */
			response.reset();  
			/* 响应头:回信的信封 */
			response.setHeader("Cache-Control", "No-cache");
			/* 弹出下载框的文件名,不支持中文 ,下载到本地以后的文件名,扩展名很重要,一定要和下载的文件扩展名一样*/
			response.setHeader("content-disposition", "attachment;filename=goods.xls");
			
			/* 下载文件:处理二进制流 
			OutputStream os = response.getOutputStream() ; 
			 准备一张图片 
			File souFile = new File("D:\\班级\\20171108\\20180330_统计_报表\\代码\\shop\\shop-web\\shop-web-back\\src\\main\\webapp\\1.png");
			FileInputStream fis = new FileInputStream(souFile);
			 文件复制 
			byte[] b = new byte[1024];
			int len = 0 ; 
			while((len = fis.read(b)) != -1)
			{
				os.write(b, 0, len);
			}
			os.close();
			fis.close();*/
			
			/* ==连接poi== */
			List<Map<String, Object>> list = (List<Map<String, Object>>) request.getAttribute("list");
			/* dataList:行
			 * Map是列:键是标题头,值是真正的结果 */
			List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
			for (Iterator iterator = list.iterator(); iterator.hasNext();)
			{
				/* 数据库中的内容 */
				Map<String, Object> map = (Map<String, Object>) iterator.next();
				ConstatFinalUtil.LOGGER.info("==结果:{}==>" ,map);
				
				/* 第一行,导出的xls里面的内容 */
				Map<String, Object> dataMap = new HashMap<String, Object>();
				dataMap.put("日期",map.get("createTime"));
				dataMap.put("总数量",map.get("totalCount"));
				dataMap.put("最大价格",map.get("maxPrice"));
				
				/* 放到List中 */
				dataList.add(dataMap);
			}
			
			/* junit测试一下,保存到文件中 
			 * 参数1:是模板
			 * 参数2:数据
			 * 参数3:保存的文件要存储的路径
			 * */
			InputStream templInputStream = ConstatFinalUtil.class.getClassLoader().getResourceAsStream("template/excel/goods.xls");
			/* 直接把POI的输出流与resonse的输入流接起来,就可以
			 * 接管子 */
			this.poiUtil.writeExcel(templInputStream, dataList, response.getOutputStream());
			return null ; 
		}
		return "/back/stat/goodsList" ; 
	}
	
	/**
	 * 商品统计
	 * @return
	 */
	@RequestMapping(value="/goodsListJSON",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String goodsListJSON(HttpServletRequest request)
	{
		ConstatFinalUtil.LOGGER.info("==goodsListJSON==");
		/* 分页模块 */
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		PageInfoUtil pageInfoUtil = this.proccedPageInfoUtil(page,rows);
		/* 搜索模块 */
		String keyword = request.getParameter("keyword");
		String status = request.getParameter("status");
		String st = request.getParameter("st");
		String ed = request.getParameter("ed");
		
		if(keyword == null)
		{
			keyword = ""; 
		}
		keyword = keyword.trim() ; 
		
		if(status == null)
		{
			status = ""; 
		}
		if(st == null)
		{
			st = ""; 
		}
		if(ed == null)
		{
			ed = ""; 
		}
		Date stDate = null ; 
		Date edDate = null ; 
		if(!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			/* 将字符串变成时间 */
			stDate = this.dateUtil.strToDateTime(st);
			edDate = this.dateUtil.strToDateTime(ed);
		}
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 清除map里面的内容 */
		condMap.clear();
		
		condMap.put("keyword", keyword);
		if(!"".equalsIgnoreCase(status))
		{
			condMap.put("status", status);
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		condMap.put("operType", "goodsStat");
		/* 调用Service的方法从数据库中取数据 */
		Map<String, Object> resultMap = this.goodsService.statGoodsService(pageInfoUtil, condMap);
		/* 凡是取值的时候,一定要确定一下里面是不是有值 */
		List<Map<String, Object>> list = (List<Map<String, Object>>) resultMap.get("list");
		int totalRecord = (int) resultMap.get("totalRecord");
		pageInfoUtil.setTotalRecord(totalRecord);
		/* 放到四大作用域中 */
		request.setAttribute("list", list);
		
		/* 拼装easyui需要的json */
		JSONObject resultJSON = new JSONObject() ; 
		resultJSON.put("total", pageInfoUtil.getTotalRecord());
		JSONArray brandArr = new JSONArray() ; 
		
		for (Iterator iterator = list.iterator(); iterator.hasNext();)
		{
			Map<String, Object> map = (Map<String, Object>) iterator.next();
			/* 将Map直接变成JSON */
			JSONObject brandJSON = (JSONObject) JSON.toJSON(map);
			brandArr.add(brandJSON);
		}
		
		resultJSON.put("rows", brandArr);
		return resultJSON.toJSONString() ; 
	}
}
